/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.center.web.action.selfmainten;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import com.sino.uam.entity.UserInfo;
import com.sinodata.bsm.center.message.Messenger;
import com.sinodata.bsm.center.service.config.ProtocolParameterService;
import com.sinodata.bsm.center.service.probe.ProbeService;
import com.sinodata.bsm.center.user.UserUtil;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.message.ServiceMessage;
import com.sinodata.bsm.common.utils.Encipher;
import com.sinodata.bsm.common.vo.Probe;
import com.sinodata.bsm.common.vo.ProtocolParameter;
import com.sinodata.notify.center.NotifyMessage;
import com.sinodata.notify.center.NotifyMessageImpl;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author wangyazhou
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-12-24 下午8:38:16          wangyazhou        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class ToolAction extends BaseAction {

    private static final long serialVersionUID = 1L;

    @Autowired
    private ProbeService probeService;

    @Autowired
    private ProtocolParameterService protocolParameterService;

    public String deCodePw() {
        JSONObject json = new JSONObject();
        String enPwd = request.getParameter("pwd");
        String dePwd = Encipher.DecodePasswd("bs?IT6VLbJ?g?f;.?s");

        System.out.println(enPwd);

        json.element("result", dePwd);
        Struts2Utils.renderText(json.toString());
        return null;
    }

    /**
     *  执行一个SSH2命令
     * @return
     */
    public String execSSH2() {
        JSONObject json = new JSONObject();
        Long probeId = Long.parseLong(request.getParameter("probeid"));
        String ip = request.getParameter("ip");
        String port = request.getParameter("port");
        String user = request.getParameter("user");
        String pwd = request.getParameter("pwd");
        String authType = request.getParameter("auth");
        String file = request.getParameter("file");
        String pool = request.getParameter("pool"); //false：不使用  ，true：使用
        String cmd = request.getParameter("cmd");

        System.out.println(authType + "--->" + file);
        ServiceMessage message = new ServiceMessage();
        message.setSrvId("SystemService");
        message.setMethod("execSSH2");
        Object[] args = { ip, port, user, authType, file, pwd, cmd, pool };
        message.setParams(args);
        String result = null;
        Object resp = null;
        try {
            resp = Messenger.getInstance().sendSyncMessage(probeId, message);
        } catch (Exception e) {
            logger.error(e);
        }
        if (resp != null) {
            result = (String) resp;
        }

        json.element("result", result);
        Struts2Utils.renderText(json.toString());
        return null;
    }

    public String execTelnet() {
        JSONObject json = new JSONObject();
        Long probeId = Long.parseLong(request.getParameter("probeid"));
        String ip = request.getParameter("ip");
        String port = request.getParameter("port");
        String user = request.getParameter("user");
        String pwd = request.getParameter("pwd");
        String pool = request.getParameter("pool"); //false：不使用  ，true：使用
        String cmd = request.getParameter("cmd");
        String prompt = request.getParameter("prompt");

        ServiceMessage message = new ServiceMessage();
        message.setSrvId("SystemService");
        message.setMethod("execTelnet");
        Object[] args = { ip, port, user, pwd, cmd, pool, prompt };
        message.setParams(args);
        String result = null;
        Object resp = null;
        try {
            resp = Messenger.getInstance().sendSyncMessage(probeId, message);
        } catch (Exception e) {
            logger.error(e);
        }
        if (resp != null) {
            result = (String) resp;
        }

        json.element("result", result);
        Struts2Utils.renderText(json.toString());

        return null;
    }

    @SuppressWarnings("unchecked")
    public String ssh2() {
        List<ProtocolParameter> protList = protocolParameterService.findByType("HOST");
        List<String> ips = new ArrayList<String>();
        for (int i = 0; i < protList.size(); i++) {
            ips.add(protList.get(i).getIp());
        }
        List<Probe> probeList = probeService.findAllCicpProbe();
        Collections.sort(probeList, new ProbeSort());
        request.setAttribute("probeList", probeList);
        request.setAttribute("ips", ips);
        return "ssh2";
    }

    /**
     * 
     * @return
     */

    @SuppressWarnings("unchecked")
    public String telnet() {
        List<ProtocolParameter> protList = protocolParameterService.findByType("HOST");
        List<String> ips = new ArrayList<String>();
        for (int i = 0; i < protList.size(); i++) {
            ips.add(protList.get(i).getIp());
        }
        List<Probe> probeList = probeService.findAllCicpProbe();
        Collections.sort(probeList, new ProbeSort());
        request.setAttribute("probeList", probeList);
        request.setAttribute("ips", ips);
        return "telnet";
    }

    public String snmp() {
        List<Probe> probeList = probeService.findAllCicpProbe();
        Collections.sort(probeList, new ProbeSort());
        request.setAttribute("probeList", probeList);
        return "snmp";
    }

    public String snmpConn() {
        JSONObject json = new JSONObject();
        try {
            Long probeId = Long.parseLong(request.getParameter("probeid"));
            String ip = request.getParameter("ip");
            String port = request.getParameter("port");
            String comunity = request.getParameter("comunity");
            String version = request.getParameter("version");
            String oid = request.getParameter("oid"); //false：不使用  ，true：使用

            ServiceMessage message = new ServiceMessage();
            message.setSrvId("SystemService");
            message.setMethod("snmpConn");
            Object[] args = { ip, port, comunity, version, oid };
            message.setParams(args);
            String result = "无返回值";
            Object resp = null;
            try {
                resp = Messenger.getInstance().sendSyncMessage(probeId, message);
            } catch (Exception e) {
                logger.error(e);
            }
            if (resp != null) {
                result = (String) resp;
            }

            json.element("result", result);
            Struts2Utils.renderText(json.toString());
        } catch (Exception e) {
            logger.error(e);
        }
        return null;
    }

    public String snmpGet() {
        JSONObject json = new JSONObject();
        Long probeId = Long.parseLong(request.getParameter("probeid"));
        String ip = request.getParameter("ip");
        String port = request.getParameter("port");
        String comunity = request.getParameter("comunity");
        String version = request.getParameter("version");
        String oid = request.getParameter("oid"); //false：不使用  ，true：使用

        String str = probeId + "_" + ip + "_" + port + "_" + comunity + "_" + version + "_" + oid;

        Struts2Utils.renderText(str);
        return null;
    }

    public String snmpGetAll() {
        JSONObject json = new JSONObject();
        Long probeId = Long.parseLong(request.getParameter("probeid"));
        String ip = request.getParameter("ip");
        String port = request.getParameter("port");
        String comunity = request.getParameter("comunity");
        String version = request.getParameter("version");
        String oid = request.getParameter("oid"); //false：不使用  ，true：使用

        String str = probeId + "_" + ip + "_" + port + "_" + comunity + "_" + version + "_" + oid;

        Struts2Utils.renderText(str);
        return null;
    }

    /**
     * 
     */
    @SuppressWarnings("rawtypes")
    public String toNotify() {
        Map<String, UserInfo> map = UserUtil.getInstance().getAllUsers();
        List<UserInfo> userList = new ArrayList<UserInfo>();
        Iterator it = map.keySet().iterator();
        while (it.hasNext()) {
            userList.add(map.get(it.next().toString()));
        }
        request.setAttribute("users", userList);
        return "notify";
    }

    /**
     * 发送测试短信
     * @return
     */
    public String sendSmsMsg() {
        String mobile = request.getParameter("mobile");
        String msg = request.getParameter("msg");
        logger.info("[TIP]\t" + mobile + " " + msg);
        NotifyMessage message = new NotifyMessageImpl(null, "", "BSM", 1, "Test", msg, mobile);
        try {
            //此类与message下的Messanger名称有冲突 
            com.sinodata.bsm.center.engine.notify.Messenger.getInstance().sendNotify(message);
        } catch (Exception e) {
            logger.error("failed to send notify message", e);
        }
        Struts2Utils.renderText("1");
        return null;
    }

    @Override
    public Object getModel() {
        return null;
    }

    @Override
    public String list() throws Exception {
        return null;
    }

    @Override
    public String input() throws Exception {
        return null;
    }

    @Override
    public String save() throws Exception {
        return null;
    }

    @Override
    public String delete() throws Exception {
        return null;
    }

    @Override
    protected void prepareModel() throws Exception {

    }

    @SuppressWarnings("rawtypes")
    class ProbeSort implements Comparator {
        public int compare(Object obj1, Object obj2) {
            Probe res1 = (Probe) obj1;
            Probe res2 = (Probe) obj2;
            if (Math.abs(res1.getStatus() - 3) > Math.abs(res2.getStatus() - 3)) {
                return 1;
            } else {
                return 0;
            }
        }
    }

    public static void main(String[] args) {
        String dePwd = Encipher.DecodePasswd("cxNJ8*?g>d:/)7DW");
        System.out.println(dePwd);
    }

}
